<template>
  <div class="role-manage-page">
    <el-card>
      <div class="header-bar">
        <span class="title">角色管理</span>
        <el-button type="primary" size="small" @click="openEditDialog()">新增角色</el-button>
      </div>
      <el-table :data="roleList" border>
        <el-table-column prop="rolename" label="角色名" min-width="120"/>
        <el-table-column prop="desc" label="描述" min-width="140"/>
        <el-table-column prop="permissions" label="权限" min-width="200">
          <template #default="scope">
            <el-tag v-for="p in scope.row.permissions" :key="p" style="margin-right:4px;">
              {{ getPermName(p) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteRole(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑/新增角色弹窗 -->
    <el-dialog v-model="dialogVisible" :title="editRole.id ? '编辑角色' : '新增角色'" width="400px">
      <el-form :model="editRole" :rules="formRules" ref="formRef" label-width="68px">
        <el-form-item label="角色名" prop="rolename">
          <el-input v-model="editRole.rolename" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="editRole.desc" />
        </el-form-item>
        <el-form-item label="权限" prop="permissions">
          <el-select v-model="editRole.permissions" multiple placeholder="请选择权限">
            <el-option v-for="perm in permList" :key="perm.id" :label="perm.name" :value="perm.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="saveRole">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 权限列表（前端模拟）
const permList = [
  { id: 'dashboard_view', name: '访问首页工作台' },
  { id: 'dataset_manage', name: '数据集管理' },
  { id: 'report_manage', name: '报表设计与管理' },
  { id: 'screen_manage', name: '大屏可视化管理' },
  { id: 'export_manage', name: '分享与导出中心' },
  { id: 'user_manage', name: '用户管理' },
  { id: 'role_manage', name: '角色管理' },
  { id: 'audit_log', name: '审计日志' },
]

// 默认角色
const defaultRoles = [
  { id: 'admin', rolename: '管理员', desc: '系统全部权限', permissions: permList.map(p => p.id) },
  { id: 'editor', rolename: '编辑者', desc: '报表和大屏编辑', permissions: ['dataset_manage', 'report_manage', 'screen_manage', 'export_manage'] },
  { id: 'viewer', rolename: '只读用户', desc: '只能浏览，不可编辑', permissions: ['dashboard_view', 'dataset_manage', 'report_manage', 'screen_manage', 'export_manage'] }
]

const roleList = ref([])

function initRoles() {
  const local = JSON.parse(localStorage.getItem('roleList') || 'null')
  if (!local) {
    localStorage.setItem('roleList', JSON.stringify(defaultRoles))
    roleList.value = defaultRoles
  } else {
    roleList.value = local
  }
}

onMounted(() => {
  initRoles()
})

function getPermName(id) {
  const p = permList.find(p => p.id === id)
  return p ? p.name : id
}

// 编辑/新增角色弹窗
const dialogVisible = ref(false)
const editRole = reactive({
  id: null,
  rolename: '',
  desc: '',
  permissions: []
})
const formRef = ref()
const formRules = {
  rolename: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
  desc: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  permissions: [{ required: true, type: 'array', min: 1, message: '请选择权限', trigger: 'change' }]
}

function openEditDialog(row = null) {
  if (row) {
    editRole.id = row.id
    editRole.rolename = row.rolename
    editRole.desc = row.desc
    // 修正：确保为数组
    editRole.permissions = Array.isArray(row.permissions) ? [...row.permissions] : []
  } else {
    editRole.id = null
    editRole.rolename = ''
    editRole.desc = ''
    editRole.permissions = []
  }
  dialogVisible.value = true
}


function saveRole() {
  formRef.value.validate((valid) => {
    if (!valid) return
    let roles = JSON.parse(localStorage.getItem('roleList') || '[]')
    if (editRole.id) {
      // 编辑
      roles = roles.map(r => r.id === editRole.id ? { ...editRole } : r)
    } else {
      // 新增
      const newId = String(Date.now())
      roles.unshift({ ...editRole, id: newId })
    }
    localStorage.setItem('roleList', JSON.stringify(roles))
    roleList.value = roles
    ElMessage.success('保存成功！')
    dialogVisible.value = false
  })
}

function deleteRole(row) {
  const roles = roleList.value.filter(r => r.id !== row.id)
  localStorage.setItem('roleList', JSON.stringify(roles))
  roleList.value = roles
  ElMessage.success('已删除！')
}
</script>

<style scoped>
.role-manage-page {
  padding: 24px;
  background: #f7f8fa;
  min-height: 95vh;
}
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.title {
  font-size: 20px;
  font-weight: 600;
}
</style>
